﻿using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace uTILLIty.Rave.Core.StorageAdapter
{
	/// <summary>
	/// Extension methods for an XmlNode
	/// </summary>
	public static class XmlNodeExtensions
	{

		/// <summary>
		/// Deserializes the current <paramref name="data">instance</paramref> to the provided type
		/// </summary>
		/// <typeparam name="T">the type to deserialize to</typeparam>
		/// <param name="data">the data to deserialize</param>
		/// <returns>a new instance of the provided type</returns>
		public static T ToObject<T>(this XmlNode data)
		{
			var xmlSerializer = new XmlSerializer(typeof(T));

			using (var memoryStream = new MemoryStream())
			{
				var doc = new XmlDocument();
				doc.AppendChild(doc.ImportNode(data, true));
				doc.Save(memoryStream);
				memoryStream.Position = 0;
				var reader = XmlReader.Create(memoryStream);
				try
				{
					return (T)xmlSerializer.Deserialize(reader);
				}
				catch
				{
					return default(T);
				}
			}
		}

	}
}